package com.nanfang51g3.ckz.ui.fragment.base;


import android.app.Activity;
import android.support.v4.app.Fragment;

import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.widget.LoadingDialog;

/**
 * Created by IME on 2016/4/21.
 */
public abstract class BaseLazyLoadFragment<T extends IPresenter>  extends Fragment {
    protected boolean isVisible;
    public LoadingDialog dialog;

    public void showPro(Activity activity, int title) {
        dialog = new LoadingDialog(activity, R.layout.view_tips_loading, title);
        dialog.setCancelable(true);//返回取消
        dialog.setCanceledOnTouchOutside(true);//触摸取消
        dialog.show();
        KLog.i("TAG", dialog == null ? "showPro==null" : "showPro!=null");
    }


    public void dismissPro() {
        KLog.i("TAG", dialog == null ? "dialog==null" : "dialog!=null");
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 如果是通过FragmentTransaction的show和hide的方法来控制显示，调用的是onHiddenChanged.
     * 若是初始就show的Fragment 为了触发该事件 需要先hide再show
     *
     * @param hidden hidden True if the fragment is now hidden, false if it is not
     *               visible.
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        KLog.e("fragment_", "onHiddenChanged  操作" + hidden);
        if (!hidden) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    /**
     * 如果是与ViewPager一起使用，调用的是setUserVisibleHint
     *
     * @param isVisibleToUser 是否显示出来了
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        KLog.e("fragment_", "setUserVisibleHint  操作" + isVisibleToUser);
        KLog.e("fragment_", "getUserVisibleHint  操作" + getUserVisibleHint());
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        KLog.i("Evd", "fragment  - onDestroyView");
        if (mPresenter != null) mPresenter.detachView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        KLog.i("Evd", "fragment - onDestroy");
    }
    protected void onVisible() {
        lazyLoad();
    }

    protected void onInvisible() {
    }

    protected abstract void lazyLoad();
    protected T mPresenter;

    /**
     * 抽象 由子类实现注入操作
     *
     * @return
     */
    public abstract T getPresenter();

    /**
     * 泛型注入操作层
     *
     * @param mPresenter
     */
    public void setPresenter(T mPresenter) {
        this.mPresenter = mPresenter;
    }
}
